package com.pms.api;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.pms.entity.BaseUser;
import com.pms.entity.UserCommunity;
import com.pms.exception.R;
import com.pms.exception.RRException;
import com.pms.service.IBaseUserService;
import com.pms.service.IUserCommunityService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import static com.pms.controller.BaseController.parameterIsNull;

/**
 * Created by hm on 2018/3/26.
 */
@RestController
@RequestMapping("apiUserCommunity")
@Api(value="App用户选择小区接口",description = "App用户选择小区接口")
public class ApiUserCommunityController {

    @Autowired
    IUserCommunityService userCommunityService;
    @Autowired
    IBaseUserService baseUserService;
    /**
     * 用户选择小区接口
     * @param userId
     * @param userCommunityId
     * @return
     */
    @GetMapping("/getUserCommunity")
    @ApiOperation("用户选择小区接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户表id", required = false, dataType = "Long", paramType = "form"),
            @ApiImplicitParam(name = "userCommunityId", value = "小区id", required = false, dataType = "Long", paramType = "form"),
    })
    public R getUserCommunity(Long userId, Long userCommunityId){
        parameterIsNull(userId,"用户Id不能为空");
        parameterIsNull(userCommunityId,"小区Id不能为空");
        BaseUser user= baseUserService.selectOne(new EntityWrapper<BaseUser>().eq("id",userId));
        parameterIsNull(user,"用户信息不存在");
        UserCommunity  userCommunity=userCommunityService.selectOne(new EntityWrapper<UserCommunity>().eq("user_id",userId).and().eq("user_community_id",userCommunityId));
        parameterIsNull(userCommunity,"用户小区信息不存在");
        if (!userCommunity.getUserId().equals(userId)){
            throw  new RRException("对不起当前用户你不匹配",400);
        }
        if (!userCommunity.getUserCommunityId().equals(userCommunityId)){
            throw  new RRException("对不起当前小区您没有权限操作",400);
        }
        UserCommunity list=userCommunityService.selectOne(new EntityWrapper<UserCommunity>().eq("thedefault",1).and().eq("user_id",userId));
        if (list==null){
            userCommunity.setThedefault(1);
        }else{
            list.setThedefault(2);
            userCommunity.setThedefault(1);
            userCommunityService.updateAllColumnById(list);
        }
        userCommunityService.updateAllColumnById(userCommunity);
        return  R.ok();
    }

}
